<template>
    <uni-popup-dialog mode="input" :title="userStore.userInfo.email?'解绑邮箱':'绑定邮箱'"
                      placeholder="请输入内容" @confirm="handle">
        <view class="flex flex-sub flex-direction">
            <view class="flex flex-sub align-center justify-between margin-xs">
                <view class="text-gray " v-if="userStore.userInfo&&userStore.userInfo.email">{{
                    userStore.userInfo.email
                    }}
                </view>
                <uni-easyinput v-else v-model="email" placeholder="请输入邮箱"></uni-easyinput>
                <button :disabled="!isSend" class="cu-btn bg-blue margin-left-xs" @click="getCode">
                    {{ isSend ? '验证码' : second }}
                </button>
            </view>
            <view class="margin-xs">
                <uni-easyinput v-model="code" placeholder="请输入验证码"></uni-easyinput>
            </view>
        </view>
    </uni-popup-dialog>
</template>

<script setup lang="ts">

import api from "@/api";
import {ref} from "vue";
import {isEmail} from "@/utils";
import {useUserStore} from "@/store";


const userStore = useUserStore()

const email = ref(userStore.userInfo.email||'')
const code = ref('')
const isSend = ref(true)
const second = ref(0)


const getCode = () => {
    if (!email.value) {
        uni.showToast({
            title: '邮箱不能为空',
            icon: 'error'
        })
        return
    }
    if (!isEmail(email.value)) {
        uni.showToast({
            title: '请输入正确邮箱',
            icon: 'error'
        })
        return
    }
    isSend.value = false
    second.value = 60
    setInterval(() => {
        second.value--
        if (second.value === 1) {
            isSend.value = true
        }
    }, 1000)
    api.mail.code({
        email: email.value
    }).then(res => {
        if (res && res.data.code !== 0) {
            isSend.value = true
        }
    })
}
const handle = () => {
    if (userStore.userInfo.email) {
        api.user.unBindEmail({
            email: email.value,
            code: code.value
        }).then(res => {
            if (res && res.data.code === 0) {
                userStore.userInfo.email = null
                email.value=''
                code.value=''
                uni.showToast({
                    title: res.data.msg
                })
            }
        })

    } else {
        api.user.bindEmail({
            email: email.value,
            code: code.value
        }).then(res => {
            if (res && res.data.code === 0) {
                userStore.userInfo.email = email.value
                code.value=''
                uni.showToast({
                    title: res.data.msg
                })
            }
        })
    }

}
</script>

<style scoped>

</style>